package com.example.text2.service.impl;

import com.example.text2.mapper.ArticleMapper;
import com.example.text2.pojo.Article;
import com.example.text2.pojo.PageBean;
import com.example.text2.service.ArticleService;
import com.example.text2.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object>map=ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id") ;
        article.setCreateUser(userId);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) {
        PageBean<Article> pageBean = new PageBean<>();
        //借助PageHelper开启分页
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object > map=ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
        List<Article>articles = articleMapper.list(userId,categoryId,state);
        // 使用PageInfo包装查询结果，获取分页信息
        PageInfo<Article> pageInfo = new PageInfo<>(articles);

        // 设置PageBean的属性
        pageBean.setTotal(pageInfo.getTotal()); // 假设PageBean有这个方法
        pageBean.setItems(articles); // 假设PageBean的items用于存储分页后的数据列表

        // 返回PageBean对象
        return pageBean;


    }
}
